<?php 

Class sysModel extends appModel
{
	/**
	 * 获得网站配置信息
	 * @return 
	 */
	public function getSetting()
	{
		$sql = "SELECT * FROM ".$this->table('options');
		$res = $this->getAll($sql);
		$arr = array();
		foreach($res as $k => $v)
		{
			$arr[$v['op_key']] = $v['op_value'];
		}
		return $arr;
	}
	
	/**
	 * 获取sql列表
	 *
	 * @access  public
	 * @param
	 *
	 * @return array
	 */
	public function get_sql_list()
	{
		$list = array();
		$path = ROOT_PATH . '/Temp/sqldata/';
		$result = array('error' => 1, 'content' => '');
		/* 检查目录 */
		$mask = file_exists($path);
		if($mask === false)
		{
			$warning = sprintf(Lang('dir_not_exist'), $path);
			$result['content']=$warning;
		}
		elseif (($mask & 1) < 1)
		{
			$warning = $path . '&nbsp;&nbsp;' . Lang('cannot_read');
			$result['content']=$warning;
		}
		else
		{
			/* 获取文件列表 */
			$real_list = array();
			$folder = opendir($path);
			while ($file = readdir($folder))
			{
				if (strpos($file,'.sql') !== false)
				{
					$real_list[] = $file;
				}
			}
			natsort($real_list);
		
			$match = array();
			foreach ($real_list AS $file)
			{
				if (preg_match('/_([0-9])+\.sql$/', $file, $match))
				{
					if ($match[1] == 1)
					{
						$mark = 1;
					}
					else
					{
						$mark = 2;
					}
				}
				else
				{
					$mark = 0;
				}
				$file_size = filesize($path . $file);
				$info = sql_dumpDB::get_head($path . $file);
				$list[] = array('name' => $file, 'ver' => $info['ecs_ver'], 'add_time' => $info['date'], 'vol' => $info['vol'], 'file_size' => $this->num_bitunit($file_size), 'mark' => $mark);
			}
		}
		return $list;
	}
	/**
	 * 将字节转成可阅读格式
	 *
	 * @access  public
	 * @param
	 *
	 * @return void
	 */
	private function num_bitunit($num)
	{
		$bitunit = array(' B',' KB',' MB',' GB');
		for ($key = 0, $count = count($bitunit); $key < $count; $key++)
		{
		if ($num >= pow(2, 10 * $key) - 1) // 1024B 会显示为 1KB
		{
		$num_bitunit_str = (ceil($num / pow(2, 10 * $key) * 100) / 100) . " $bitunit[$key]";
		}
		}
	
		return $num_bitunit_str;
		}
	public function import($file_name)
	{
		/* 权限判断 */
		
		$result=array('error'=>1,'content'=>'');
		$is_confirm = empty($_GET['confirm']) ? false : true;
		$path = ROOT_PATH . '/Temp/sqldata/';
	    if($file_name=='')
	   {
		  die();
	   }
		
		/* 设置最长执行时间为5分钟 */
		@set_time_limit(300);
	
		if (preg_match('/_[0-9]+\.sql$/', $file_name))
		{
			/* 多卷处理 */
			if ($is_confirm == false)
			{
				/* 提示用户要求确认 */
				//sys_msg($_LANG['confirm_import'], 1, array(array('text'=>$_LANG['also_continue'], 'href'=>'database.php?act=import&confirm=1&file_name=' . $file_name)), false);
			
			exit();
			}
	
			$short_name = substr($file_name, 0, strrpos($file_name, '_'));
	
			/* 获取文件列表 */
			$real_file = array();
			$folder = opendir($path);
			while ($file = readdir($folder))
			{
				if (is_file($path . $file) && preg_match('/_[0-9]+\.sql$/', $file))
				{
					$real_file[] = $file;
				}
			}
	
			/* 所有相同分卷数据列表 */
			$post_list = array();
			foreach ($real_file AS $file)
			{
				$tmp_name = substr($file, 0, strrpos($file, '_'));
				if ($tmp_name == $short_name)
				{
					$post_list[] = $file;
				}
			}
	
			natsort($post_list);
	
			/* 开始恢复数据 */
			foreach ($post_list AS $file)
			{
				$info = sql_dumpDB::get_head($path . $file);
				if ($info['ecs_ver'] != VERSION )
				{
					//sys_msg(sprintf($_LANG['version_error'], VERSION, $sql_info['ecs_ver']));
				}
				if (!sql_import($path . $file))
				{
					//sys_msg($_LANG['sqlfile_error'], 1);
					$result['content']=Lang('sql_error');
					
					return $result;
				}
			}
	
			
	
			//sys_msg($_LANG['restore_success'], 0, array(array('text'=>$_LANG['restore'], 'href'=>'database.php?act=restore')));
			$result['error']=0;
			$result['content']=Lang('restore_success');
			return $result;
		}
		else
		{
			/* 单卷 */
			$info = sql_dumpDB::get_head($path . $file_name);
			if ($info['ecs_ver'] != VERSION )
			{
				//sys_msg(sprintf($_LANG['version_error'], VERSION, $sql_info['ecs_ver']));
			}
			
			if ($this->sql_import($path . $file_name))
			{
				
			
				//sys_msg($_LANG['restore_success'], 0, array(array('text'=>$_LANG['restore'], 'href'=>'database.php?act=restore')));
				$result['error']=0;
				$result['content']=Lang('restore_success');
			
			}
			else
			{
				//sys_msg($_LANG['sqlfile_error'], 1);
				$result['content']=Lang('sql_error');
			}
			return $result;
		}
	}
	/**
	 *
	 * 恢复数据库
	 * @access  public
	 * @param
	 *
	 * @return void
	 */
	private function sql_import($sql_file)
	{
		$db_ver  = $this->db->version();
	
		$sql_str = array_filter(file($sql_file), 'remove_comment');
		
	
		$sql_str = str_replace("\r", '', implode('', $sql_str));
	
		$ret = explode(";\n", $sql_str);
		$ret_count = count($ret);
	
		/* 执行sql语句 */
		if ($db_ver > '4.1')
		{
			for($i = 0; $i < $ret_count; $i++)
			{
			$ret[$i] = trim($ret[$i], " \r\n;"); //剔除多余信息
					if (!empty($ret[$i]))
					{
					if ((strpos($ret[$i], 'CREATE TABLE') !== false) && (strpos($ret[$i], 'DEFAULT CHARSET='. str_replace('-', '', EC_CHARSET) )=== false))
					{
							/* 建表时缺 DEFAULT CHARSET=utf8 */
							$ret[$i] = $ret[$i] . 'DEFAULT CHARSET='. str_replace('-', '', EC_CHARSET);
					}
					$this->db->query($ret[$i]);
					}
					}
					}
					else
								{
								for($i = 0; $i < $ret_count; $i++)
								{
									$ret[$i] = trim($ret[$i], " \r\n;"); //剔除多余信息
										if ((strpos($ret[$i], 'CREATE TABLE') !== false) && (strpos($ret[$i], 'DEFAULT CHARSET='. str_replace('-', '', EC_CHARSET) )!== false))
            {
											$ret[$i] = str_replace('DEFAULT CHARSET='. str_replace('-', '', EC_CHARSET), '', $ret[$i]);
										}
										if (!empty($ret[$i]))
										{
											$this->db->query($ret[$i]);
		}
		}
		}
	
		return true;
		}
	/**
	 * 备份数据库数据
	 * @return 
	 */
	public function backup()
	{
		$db = $this->db;
		global $prefix;
		
		$path = ROOT_PATH .'/Temp/sqldata';
		$mask = file_exists($path);
		$result = array('error' => 1, 'content' => '');
		if($mask === false)
		{
			$warning = sprintf(Lang('dir_not_exist'), $path);
			$result['content']=$warning;
			return $result;
		}
		elseif ($mask != 15)
		{
			$warning = sprintf(Lang('dir_priv'), $path);
			if (($mask&1) < 1)
			{
				$warning .= Lang('cannot_read');
			}
			if (($mask & 2) < 1)
			{
				$warning .= Lang('cannot_write');
			}
			if (($mask & 4) < 1)
			{
				$warning .= Lang('cannot_add');
			}
			if (($mask & 8) < 1)
			{
				$warning .= Lang('cannot_modify');
			}
			$result['content']=$warning;
			return $result;
		}
	
		/* 设置最长执行时间为5分钟 */
		@set_time_limit(300);
	
		/* 初始化 */
		$dump = new sql_dumpDB($db);
		$run_log = ROOT_PATH .'/Temp/sqldata/run.log';
	
		/* 初始化输入变量 */
		if (empty($_REQUEST['sql_file_name']))
		{
			$sql_file_name = $dump->get_random_name();
		}
		else
		{
			$sql_file_name = str_replace("0xa", '', trim($_REQUEST['sql_file_name'])); // 过滤 0xa 非法字符
			$pos = strpos($sql_file_name, '.sql');
			if ($pos !== false)
			{
				$sql_file_name = substr($sql_file_name, 0, $pos);
			}
		}
	
		$max_size = empty($_REQUEST['vol_size']) ? 0 : intval($_REQUEST['vol_size']);
		$vol = empty($_REQUEST['vol']) ? 1 : intval($_REQUEST['vol']);
		$is_short = empty($_REQUEST['ext_insert']) ? false : true;
	
		$dump->is_short = $is_short;
	
		/* 变量验证 */
		$allow_max_size = intval(@ini_get('upload_max_filesize')); //单位M
		if ($allow_max_size > 0 && $max_size > ($allow_max_size * 1024))
		{
			$max_size = $allow_max_size * 1024; //单位K
		}
	
		if ($max_size > 0)
		{
			$dump->max_size = $max_size * 1024;
		}
	
		/* 获取要备份数据列表 */
		$type = empty($_POST['type']) ? 'full' : trim($_POST['type']);
		$tables = array();
	
		switch ($type)
		{
			case 'full':
				$except = array($prefix.'sessions', $prefix.'sessions_data');
				$temp = $db->GetCol("SHOW TABLES LIKE '" . mysql_like_quote($prefix) . "%'");
				foreach ($temp AS $table)
				{
					if (in_array($table, $except))
					{
						continue;
					}
					$tables[$table] = -1;
				}
	
				$dump->put_tables_list($run_log, $tables);
				break;
	
			case 'stand':
				$temp = array('admin_user','area_region','article','article_cat','attribute','brand','cart','category','comment','goods','goods_attr','goods_cat','goods_gallery','goods_type','group_goods','link_goods','member_price','order_action','order_goods','order_info','payment','region','shipping','shipping_area','shop_config','user_address','user_bonus','user_rank','users','virtual_card');
				foreach ($temp AS $table)
				{
					$tables[$ecs->prefix . $table] = -1;
				}
				$dump->put_tables_list($run_log, $tables);
				break;
	
			case 'min':
				$temp = array('attribute','brand','cart','category','goods','goods_attr','goods_cat','goods_gallery','goods_type','group_goods','link_goods','member_price','order_action','order_goods','order_info','shop_config','user_address','user_bonus','user_rank','users','virtual_card');
				foreach ($temp AS $table)
				{
					$tables[$ecs->prefix . $table] = -1;
				}
				$dump->put_tables_list($run_log, $tables);
				break;
			case 'custom':
				foreach ($_POST['customtables'] AS $table)
				{
					$tables[$table] = -1;
				}
				$dump->put_tables_list($run_log, $tables);
				break;
		}
		
		/* 开始备份 */
		$tables = $dump->dump_table($run_log, $vol);
		
		if ($tables === false)
		{
			die($dump->errorMsg());
		}
		
		if (empty($tables))
		{
			/* 备份结束 */
			if ($vol > 1)
			{
				/* 有多个文件 */
				if (!@file_put_contents(ROOT_PATH . '/Temp/sqldata/' . $sql_file_name . '_' . $vol . '.sql', $dump->dump_sql))
				{
					//sys_msg(sprintf($_LANG['fail_write_file'], $sql_file_name . '_' . $vol . '.sql'), 1, array(array('text'=>$_LANG['02_db_manage'], 'href'=>'database.php?act=backup')), false);
					$result['content']=Lang('backup_fail');
					return $result;
				
				}
				$list = array();
				for ($i = 1; $i <= $vol; $i++)
				{
				$list[] = array('name'=>$sql_file_name . '_' . $i . '.sql', 'href'=>'../' . DATA_DIR . '/sqldata/' . $sql_file_name . '_' . $i . '.sql');
				}
				$result['error']=0;
				$result['content']=Lang('backup_success');
				
				return $result;
				
	
			}
			else
			{
			/* 只有一个文件 */
					if (!@file_put_contents(ROOT_PATH . '/Temp/sqldata/' . $sql_file_name . '.sql', $dump->dump_sql))
					{
					$result['content']=Lang('backup_fail');
					
				   }
				   else 
				   {
				   	$result['error']=0;
				   	$result['content']=Lang('backup_success');
				   }
				   
				   return $result;
				  
			}
		}
		else
		{
				/* 下一个页面处理 */
		    if (!@file_put_contents(ROOT_PATH .'/Temp/sqldata/' . $sql_file_name . '_' . $vol . '.sql', $dump->dump_sql))
			{
					$result['content']=Lang('backup_fail');
					
			}
			else
			{
				$result['error']=0;
				$result['content']=Lang('backup_success');
				
			}
	
			return $result;
		}
			
	}
	
	/**
	 * 保存网站设置
	 */
	public function saveSetting($info)
	{
		foreach($info as $k=>$v)
		{
			$sql="UPDATE ".$this->table('options')." SET op_value='$v' WHERE op_key='$k'";
			$res=$this->query($sql);
		}
		return true;
	}
	
}